package org.vectrics.recruiter.struts.admin;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.ecs.html.Form;
import org.apache.ecs.html.TextArea;
import org.vectrics.SystemException;
import org.vectrics.common.html.Combo;
import org.vectrics.common.util.StringUtils;
import org.vectrics.common.view.HtmlForm;
import org.vectrics.common.view.HtmlFormEditRow;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;
import org.vectrics.user.PersonCommunication;
import org.vectrics.user.PersonCommunicationReasonType;
import org.vectrics.user.PersonEncounterStatusType;

public class PersonPhoneCallFormTag extends VectricsTagSupport {
	static final long serialVersionUID = 234524344324323L;

	private String personId = null;
	private String personCommunicationId = null;
	private boolean edit = true;

	@Override
	protected String makeStartTag() {
		Person person = null;
		PersonCommunication personCommunication = null;
        
		if (StringUtils.isNullOrBlank(this.personCommunicationId) == false) {
			this.personCommunicationId = this.getRequest().getParameter(
					"personCommunicationId");
		}

		if (StringUtils.isNullOrBlank(this.personCommunicationId) == false) {
			personCommunication = CoreServiceLocator.getPersonService()
					.findPersonCommunication(new Long(personCommunicationId));
			person = personCommunication.getPerson();
			this.personId = person.getId().toString();
		} else if (StringUtils.isNullOrBlank(this.personId) == false) {
			person = CoreServiceLocator.getPersonService().findPersonById(
					new Long(this.personId));
		} else {
			throw new SystemException(
					"This tag requires personId or personCommunicationId to be specified");
		}

		PersonPhoneCallForm actionForm = (PersonPhoneCallForm) this
				.getRequest().getAttribute("personPhoneCallForm");
		if (actionForm == null) {
			throw new SystemException("No action form attached to request");
		}

		HtmlForm form = new HtmlForm(this.getRequest(), "personPhoneCallForm", this.getPhrase("phrase.phone.call.information"));
		form.setAction("/hrs-intranet/admin/user/encounter/savePhoneCall.do");
		form.setMethod(Form.POST);
		if (personCommunication != null) {
			form.addHidden("id", personCommunication.getId().toString());
		}
        if (this.isEdit()) {
        	this.addCommunicationMethodCombo(form);
        	this.addEncounterStatusTypeCombo(form);
        	form.addPersonPicker(this.getPhrase("prompt.encounter.from.person"), "fromPersonId", this.getContextPath(), true);
    		HtmlFormEditRow rowToPerson = (HtmlFormEditRow) form.addEditForParam(this.getPhrase("prompt.encounter.to.person"), "toPersonId", false);
    		rowToPerson.getEditBox().setDisabled(true);
    		rowToPerson.getEditBox().setValue(person.getFullName());
    		form.addHidden("toPersonId", personId);
    		form.addDatePickerForParam(this.getPhrase("prompt.date") + " *", "startDate");
    		form.addTimeEditForParam(this.getPhrase("prompt.time"), "startHour",
    				"startMinute", "startAmPm", true);
    		HtmlFormEditRow minutesRow = (HtmlFormEditRow) form.addEditForParam(this.getPhrase("prompt.minutes"), "minutes", false);
    		minutesRow.getEditBox().setMaxlength(3);
    		minutesRow.getEditBox().setOnKeyPress(" return soloNumerosEnteros(event, this);");

        } else {
        	HtmlFormEditRow rowFromPerson = (HtmlFormEditRow) form.addEditForParam(this.getPhrase("prompt.encounter.from.person"), "fromPersonId", false);
        	rowFromPerson.getEditBox().setDisabled(true);
        	if (personCommunication.getLeadPerson()!=null) {
        		rowFromPerson.getEditBox().setValue(personCommunication.getLeadPerson().getFullName());
        	}
    		HtmlFormEditRow rowToPerson = (HtmlFormEditRow) form.addEditForParam(this.getPhrase("prompt.encounter.to.person"), "toPersonId", false);
    		rowToPerson.getEditBox().setDisabled(true);
    		rowToPerson.getEditBox().setValue(person.getFullName());
    		form.addHidden("toPersonId", personId);
        }
				
		TextArea textArea = form.addTextAreaRowForParam(this.getPhrase("prompt.encounter.callDescription"), "notes", 6, 60, false);
        textArea.setDisabled(!this.isEdit());

		form.addHidden("personId", personId);
	    
		if (this.isEdit()) {
			addReasonCheckBoxes(form, personCommunication);
			form.addSubmitAndCancelButton();			
		}

		return (form.toString() + "\r\n<!-- End of form tag output -->");
	}

	public String getPersonCommunicationId() {
		return personCommunicationId;
	}

	public void setPersonCommunicationId(String personCommunicationId) {
		this.personCommunicationId = personCommunicationId;
	}

	public String getPersonId() {
		return personId;
	}

	public void setPersonId(String personId) {
		this.personId = personId;
	}

	private void addReasonCheckBoxes(HtmlForm form, PersonCommunication personCommunication) {
		form.addSection("Reason(s)", null);

		List reasons = CoreServiceLocator.getPersonService().findAllPersonCommunicationReasonTypes();
		log.info("Reasons count: " + reasons.size());
		Iterator iter = reasons.iterator();
		while (iter.hasNext()) {
			PersonCommunicationReasonType reasonType = (PersonCommunicationReasonType)iter.next();
			
			boolean reasonSelected = false;

			if (personCommunication != null) {
				log.debug("Reload personCommunication, lazy loading doesn't work otherwise");
				personCommunication = CoreServiceLocator.getPersonService().findPersonCommunication(personCommunication.getId());
				reasonSelected = personCommunication.hasReasonType(reasonType);
			}
			
			form.addCheckbox(this.getPhrase(reasonType.getDescriptionCode()), "reason_" + reasonType.getCode(),
					reasonSelected);
			
		}
	}

	
	private void addCommunicationMethodCombo(HtmlForm form) {
		Combo combo = new Combo();
		combo.setClass("formComboClass");
		combo.addOption("Phone Call", "phone");
		combo.addOption("Email", "email");
		combo.addOption("Uncertain", "uncertain");

		form.addComboRowForParam(this.getPhrase("prompt.encounter.method"),
				"methodCode", combo, true);
	}

	private void addEncounterStatusTypeCombo(HtmlForm form) {
		Collection allEncounterStatusTypes = CoreServiceLocator
				.getPersonService().findAllPersonEncounterStatusTypes();
		Iterator iter = allEncounterStatusTypes.iterator();
		Combo combo = new Combo();
		combo.setClass("formComboClass");
		while (iter.hasNext()) {
			PersonEncounterStatusType encounterType = (PersonEncounterStatusType) iter
					.next();
			combo.addOption(encounterType.getName(), encounterType.getCode());
		}
		// seleccionamos la opcion Completed por default.
		combo.selectOption("completed");

		form.addComboRowForParam(this.getPhrase("prompt.encounter.status"),
				"encounterStatusCode", combo, true);
	}

	/**
	 * @return the edit
	 */
	public boolean isEdit() {
		return edit;
	}

	/**
	 * @param edit the edit to set
	 */
	public void setEdit(boolean edit) {
		this.edit = edit;
	}
	
}
